/* ===========================================================
 * NetworkEvolutionPlugin : Cytoscape plugin for visualizing stages of
 * protein networks evolution.
 * ===========================================================
 *
 *
 * Project Info:  http://bioputer.mimuw.edu.pl/modevo/
 * Sources: http://code.google.com/p/misiek/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * NetworkEvolutionPlugin  Copyright (C) 2008-2010
 * Authors:  Michal Wozniak (code) (m.wozniak@mimuw.edu.pl)
 *           Janusz Dutkowski (idea, data) (j.dutkowski@mimuw.edu.pl)
 *           Jerzy Tiuryn (supervisor) (tiuryn@mimuw.edu.pl)
 */
package ppine.ui.dataloading;

import ppine.io.AbstractDataReader;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import javax.help.HelpBroker;
import javax.swing.JFileChooser;
import ppine.help.PPINEHelpBroker;
import ppine.io.listeners.InteractionsLoadingErrorsListener;
import ppine.logicmodel.controllers.DataHandle;
import ppine.logicmodel.structs.Interaction;
import ppine.logicmodel.structs.PPINetwork;
import ppine.logicmodel.structs.SpeciesTreeNode;
import ppine.main.LoadedDataHandle;
import ppine.main.PluginDataHandle;
import ppine.ui.listeners.InteractionsLoadedListener;

/**
 *
 * @author misiek
 */
public class InteractionsLoaderPanel extends javax.swing.JPanel {

    Collection<SpeciesInteractionsLoaderPanel> panels = new Vector<SpeciesInteractionsLoaderPanel>();
    Collection<OneFileSpeciesInteractionsLoaderPanel> oneFilePanels = new Vector<OneFileSpeciesInteractionsLoaderPanel>();
    InteractionsLoadedListener list;
    String onefilepath;
    DataLoaderPanel loaderPanel;

    public InteractionsLoaderPanel(InteractionsLoadedListener list) {
        this.list = list;
        initComponents();
        initSpeciesListForOneFile();
        initSpeciesList();
        setActualUIState();
    }

    public void setStateChoosen() {
        loadButton.setEnabled(true);
        cleanButton.setEnabled(false);
    }

    public void setStateLoaded() {
        loadButton.setEnabled(false);
        cleanButton.setEnabled(true);
    }

    public void setStateClean() {
        loadButton.setEnabled(false);
        cleanButton.setEnabled(false);
    }

    public void setLoaderPanel(DataLoaderPanel loaderPanel) {
        this.loaderPanel = loaderPanel;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        loadButton = new javax.swing.JButton();
        infoButton = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        oneLodingPanel = new javax.swing.JPanel();
        chooseOneFileButton = new javax.swing.JButton();
        oneFileLoadingPanel = new javax.swing.JPanel();
        oneFilenameLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        loadingPanel = new javax.swing.JPanel();
        cleanButton = new javax.swing.JButton();

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        loadButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ppine/resources/icons/save.png"))); // NOI18N
        loadButton.setText("Load");
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("ppine/ui/dataloading/Bundle"); // NOI18N
        loadButton.setToolTipText(bundle.getString("UpdateInteractionsButton.ToolTip")); // NOI18N
        loadButton.setName("loadButton"); // NOI18N
        loadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadButtonActionPerformed(evt);
            }
        });

        infoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ppine/resources/icons/help.png"))); // NOI18N
        infoButton.setText("File format info");
        infoButton.setToolTipText(bundle.getString("FileFormatInfoInteractionsButton.ToolTip")); // NOI18N
        infoButton.setName("infoButton"); // NOI18N
        infoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                infoButtonActionPerformed(evt);
            }
        });

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        oneLodingPanel.setName("oneLodingPanel"); // NOI18N

        chooseOneFileButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ppine/resources/icons/com.png"))); // NOI18N
        chooseOneFileButton.setText("Choose file");
        chooseOneFileButton.setName("chooseOneFileButton"); // NOI18N
        chooseOneFileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chooseOneFileButtonActionPerformed(evt);
            }
        });

        oneFileLoadingPanel.setName("oneFileLoadingPanel"); // NOI18N

        javax.swing.GroupLayout oneFileLoadingPanelLayout = new javax.swing.GroupLayout(oneFileLoadingPanel);
        oneFileLoadingPanel.setLayout(oneFileLoadingPanelLayout);
        oneFileLoadingPanelLayout.setHorizontalGroup(
            oneFileLoadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 525, Short.MAX_VALUE)
        );
        oneFileLoadingPanelLayout.setVerticalGroup(
            oneFileLoadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 412, Short.MAX_VALUE)
        );

        oneFilenameLabel.setText("filename");
        oneFilenameLabel.setName("oneFilenameLabel"); // NOI18N

        javax.swing.GroupLayout oneLodingPanelLayout = new javax.swing.GroupLayout(oneLodingPanel);
        oneLodingPanel.setLayout(oneLodingPanelLayout);
        oneLodingPanelLayout.setHorizontalGroup(
            oneLodingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(oneLodingPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chooseOneFileButton, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(oneFilenameLabel)
                .addGap(249, 249, 249))
            .addGroup(oneLodingPanelLayout.createSequentialGroup()
                .addComponent(oneFileLoadingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        oneLodingPanelLayout.setVerticalGroup(
            oneLodingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(oneLodingPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(oneLodingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(chooseOneFileButton)
                    .addComponent(oneFilenameLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(oneFileLoadingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jScrollPane3.setViewportView(oneLodingPanel);

        jTabbedPane1.addTab("Single file", jScrollPane3);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        loadingPanel.setName("loadingPanel"); // NOI18N

        javax.swing.GroupLayout loadingPanelLayout = new javax.swing.GroupLayout(loadingPanel);
        loadingPanel.setLayout(loadingPanelLayout);
        loadingPanelLayout.setHorizontalGroup(
            loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 535, Short.MAX_VALUE)
        );
        loadingPanelLayout.setVerticalGroup(
            loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 463, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(loadingPanel);

        jTabbedPane1.addTab("Multiple files", jScrollPane1);

        cleanButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ppine/resources/icons/clean.png"))); // NOI18N
        cleanButton.setText("Clean");
        cleanButton.setToolTipText(bundle.getString("CleanInteractionsButton.ToolTip")); // NOI18N
        cleanButton.setName("cleanButton"); // NOI18N
        cleanButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cleanButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(loadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cleanButton, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 175, Short.MAX_VALUE)
                .addComponent(infoButton)
                .addContainerGap())
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(infoButton)
                    .addComponent(cleanButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 491, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    public void initSpeciesListForOneFile() {
        LoadedDataHandle ldh = PluginDataHandle.getLoadedDataHandle();
        DataHandle dh = PluginDataHandle.getDataHandle();
        if (!ldh.isProteinsLoaded()) {
            return;
        }
        oneFileLoadingPanel.setLayout(new GridLayout(dh.getNetworks().keySet().size(), 1));

        for (String species : dh.getNetworks().keySet()) {
            OneFileSpeciesInteractionsLoaderPanel panel = new OneFileSpeciesInteractionsLoaderPanel(species);
            oneFilePanels.add(panel);
            oneFileLoadingPanel.add(panel);
        }
    }

    private void refreshLoadingUI() {
        oneFilenameLabel.setText("filename");
        refreshSpeciesList();
        refreshSpeciesListForOneFile();
    }

    private void refreshSpeciesList() {
        LoadedDataHandle dh = PluginDataHandle.getLoadedDataHandle();
        if (!dh.isProteinsLoaded()) {
            return;
        }

        for (SpeciesInteractionsLoaderPanel panel : panels) {

            panel.setActualLoadedUIState();
        }
    }

    private void refreshSpeciesListForOneFile() {
        LoadedDataHandle dh = PluginDataHandle.getLoadedDataHandle();
        if (!dh.isProteinsLoaded()) {
            return;
        }

        for (OneFileSpeciesInteractionsLoaderPanel panel : oneFilePanels) {

            panel.setActualLoadedUIState();
        }
    }

    private void setActualUIState() {
        if (PluginDataHandle.getLoadedDataHandle().fromOneFileLoaded()) {
            setOneFileTabEnabled();
            setOneFileTabSelected();
            cleanButton.setEnabled(true);
            loadButton.setEnabled(true);
            onefilepath = PluginDataHandle.getLoadedDataHandle().getOneInteractionFilename();
            oneFilenameLabel.setText(onefilepath);
        } else if (PluginDataHandle.getLoadedDataHandle().fromManyFilesLoaded()) {
            setManyFilesTabEnabled();
            setManyFilesTabSelected();
            cleanButton.setEnabled(true);
            loadButton.setEnabled(true);
        } else {
            loadButton.setEnabled(false);
            cleanButton.setEnabled(false);
            setBothTabEnabled();
            setOneFileTabSelected();
        }
    }

    private void setManyFilesTabSelected() {
        jTabbedPane1.setSelectedIndex(1);
    }

    private void setManyFilesTabEnabled() {

        jTabbedPane1.setEnabledAt(0, false);
        jTabbedPane1.setEnabledAt(1, true);
    }

    private void setOneFileTabEnabled() {
        jTabbedPane1.setEnabledAt(0, true);
        jTabbedPane1.setEnabledAt(1, false);
    }

    private void setBothTabEnabled() {
        jTabbedPane1.setEnabledAt(0, true);
        jTabbedPane1.setEnabledAt(1, true);
    }

    private void setOneFileTabSelected() {
        jTabbedPane1.setSelectedIndex(0);
    }

    private boolean isManyFilesSelected() {
        int index = jTabbedPane1.getSelectedIndex();
        return (index == 1);
    }

    public void initSpeciesList() {
        LoadedDataHandle ldh = PluginDataHandle.getLoadedDataHandle();
        DataHandle dh = PluginDataHandle.getDataHandle();
        if (!ldh.isProteinsLoaded()) {
            return;
        }

        loadingPanel.setLayout(new GridLayout(dh.getNetworks().keySet().size(), 1));

        for (String species : dh.getNetworks().keySet()) {
            if (!species.contains("EXP")) {
                SpeciesInteractionsLoaderPanel panel = new SpeciesInteractionsLoaderPanel(species, this);
                panels.add(panel);
                loadingPanel.add(panel);
            }
        }
    }

    private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
        cleanButton.setEnabled(true);
        if (isManyFilesSelected()) {
            updateFromManyFiles();
            setManyFilesTabEnabled();
        } else {
            updateFromOneFile();
            setOneFileTabEnabled();
        }
}//GEN-LAST:event_loadButtonActionPerformed

    private void infoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infoButtonActionPerformed
       // CSH.DisplayHelpFromSource csh = new CSH.DisplayHelpFromSource(PPINEHelpBroker.getHelpBroker("Interactions file format"));
       // csh.actionPerformed(new ActionEvent(this, 120, "Interactions file format"));
        HelpBroker helpBroker = PPINEHelpBroker.getHelpBroker("Interactions");
        //CSH.DisplayHelpFromSource csh = new CSH.DisplayHelpFromSource(helpBroker);
        helpBroker.initPresentation();
        helpBroker.setDisplayed(true);
    }//GEN-LAST:event_infoButtonActionPerformed

    private void cleanButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cleanButtonActionPerformed
        DefaultLoadingController.deleteAllInteractions();
        refreshLoadingUI();
        setBothTabEnabled();
        loadButton.setEnabled(false);
        cleanButton.setEnabled(false);
    }//GEN-LAST:event_cleanButtonActionPerformed

    private void chooseOneFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseOneFileButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(fc);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            onefilepath = file.getAbsolutePath();
            oneFilenameLabel.setText(onefilepath);
            loadButton.setEnabled(true);
        }
    }//GEN-LAST:event_chooseOneFileButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton chooseOneFileButton;
    private javax.swing.JButton cleanButton;
    private javax.swing.JButton infoButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JButton loadButton;
    private javax.swing.JPanel loadingPanel;
    private javax.swing.JPanel oneFileLoadingPanel;
    private javax.swing.JLabel oneFilenameLabel;
    private javax.swing.JPanel oneLodingPanel;
    // End of variables declaration//GEN-END:variables

    private void readAISpeciesInteractions(PPINetwork network, String filepath, Double treshold, Double oldTreshold) {
        InteractionsLoadingErrorsListener errorListener = new InteractionsLoadingErrorsListener(loaderPanel);

        if (treshold == null && oldTreshold == null) {
            return;
        } else if (treshold == null && oldTreshold != null) {
            network.deleteAllInteractions();
            AbstractDataReader.getInstance().readSpeciesInteractions(network, filepath, treshold, errorListener);
        } else if (treshold != null && oldTreshold == null) {
            network.deleteAllInteractions();
            AbstractDataReader.getInstance().readSpeciesInteractions(network, filepath, treshold, errorListener);
        } else if (treshold < oldTreshold) {
            network.deleteAllInteractions();
            AbstractDataReader.getInstance().readSpeciesInteractions(network, filepath, treshold, errorListener);
        } else if (treshold > oldTreshold) {
            Collection<Interaction> intBackup = new HashSet<Interaction>(network.getInteractions().values());
            for (Interaction inter : intBackup) {
                if (inter.getProbability() < treshold) {
                    network.deleteInteraction(inter.getID());
                }
            }

        } else {   // treshold == oldTreshold
            return;
        }
    }

    private void updateFromManyFiles() {
        for (SpeciesInteractionsLoaderPanel speciesPanel : panels) {

            String speciesName = speciesPanel.getSpeciesName();
            PPINetwork network = PluginDataHandle.getDataHandle().getPPINetwork(speciesName);
            if (speciesPanel.checked()) {
                String filename = speciesPanel.tryGetFilepath();
                if (filename != null) {
                    Double oldTresholdOrNull = PluginDataHandle.getLoadedDataHandle().getSpeciesInteractionsTreshold(speciesName);
                    Double tresholdOrNull = speciesPanel.tryGetTreshold();
                    updateInteractionsDataForSpecies(network, speciesName, filename, tresholdOrNull, oldTresholdOrNull);
                }
            } else {
                network.deleteAllInteractions();
                PluginDataHandle.getLoadedDataHandle().deleteInteractionData(speciesName);
            }
        }
        list.actionPerformed(new ActionEvent(this, 3, "Interactions loaded"));
    }

    private void updateFromOneFile() {
        if (onefilepath != null) {
            InteractionsLoadingErrorsListener errorListener = new InteractionsLoadingErrorsListener(loaderPanel);
            Map<String, Double> tresholds = new TreeMap<String, Double>();
            PluginDataHandle.getLoadedDataHandle().setOneInteractionFilename(onefilepath);
            for (OneFileSpeciesInteractionsLoaderPanel oneFileSpeciesPanel : oneFilePanels) {

                String speciesName = oneFileSpeciesPanel.getSpeciesName();
                SpeciesTreeNode network = PluginDataHandle.getDataHandle().getNetworks().get(speciesName);
                network.deleteAllInteractions();
                PluginDataHandle.getLoadedDataHandle().deleteInteractionData(speciesName);
                if (oneFileSpeciesPanel.checked()) {
                    Double tresholdOrNull = oneFileSpeciesPanel.tryGetTreshold();
                    tresholds.put(speciesName, tresholdOrNull);
                    PluginDataHandle.getLoadedDataHandle().addInteractionOneFileData(speciesName, tresholdOrNull);
                }
            }
            AbstractDataReader reader = AbstractDataReader.getInstance();
            reader.readAllInteractions(onefilepath, tresholds, errorListener);
            list.actionPerformed(new ActionEvent(this, 3, "Interactions loaded"));
        }
    }

    private void updateInteractionsDataForSpecies(PPINetwork network, String speciesName, String filename, Double tresholdOrNull, Double oldTresholdOrNull) {
        LoadedDataHandle ldh = PluginDataHandle.getLoadedDataHandle();
        if (ldh.loadedInteractions(speciesName)) {
            //Double oldTresholdOrNull = ldh.getSpeciesInteractionsTreshold(speciesName);
            ldh.deleteInteractionData(speciesName);
            // network.deleteAllInteractions();

            ldh.addInteractionData(speciesName, filename, tresholdOrNull);
            readAISpeciesInteractions(network, filename, tresholdOrNull, oldTresholdOrNull);
            //       AbstractDataReader.getInstance().readAISpeciesInteractions(network, filename, tresholdOrNull, oldTresholdOrNull);
        } else {
            InteractionsLoadingErrorsListener errorListener = new InteractionsLoadingErrorsListener(loaderPanel);
            ldh.addInteractionData(speciesName, filename, tresholdOrNull);
            AbstractDataReader.getInstance().readSpeciesInteractions(network, filename, tresholdOrNull, errorListener);
        }
    }

    void enableLoadButton() {
        loadButton.setEnabled(true);
    }
}
